<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    @ok="handleSubmit"
    :footer="null"
  >
    <Card title="选择表单域" :headStyle="{ textAlign: 'center' }">
      <div class="w-1/2 m-auto flex">
        <Select
          v-model:value="selectedValue"
          class="w-full"
          mode="multiple"
          show-search
          allow-clear
          :filterOption="(input: string, option: any) => {
                          return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
                        }"
        >
          <SelectOption
            v-for="item in options"
            :label="item.title"
            :value="item.name"
            :key="item.name"
          >
            {{ item.title }}
          </SelectOption>
        </Select>
        <a-button type="primary" class="ml-2" @click="handleForm">确定</a-button>
      </div>
    </Card>
    <Card title="选择嵌套表单域" :headStyle="{ textAlign: 'center' }">
      <div class="w-1/2 m-auto flex">
        <Select
          v-model:value="selectedValue2"
          class="w-full"
          mode="multiple"
          allow-clear
          show-search
          :filterOption="(input: string, option: any) => {
                          return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
                        }"
        >
          <SelectOption
            v-for="item in options2"
            :value="item.name"
            :key="item.name"
            :label="item.title"
          >
            {{ item.title }}
          </SelectOption>
        </Select>
        <a-button type="primary" class="ml-2" @click="handleFormNest">确定</a-button>
      </div>
    </Card>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, reactive, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { Select, Card } from 'ant-design-vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { isArray } from '/@/utils/is';
  import { getFormGetNestFields } from '/@/api/flowManage/flowManage';

  interface DataList {
    label: string;
    value: string;
  }

  export default defineComponent({
    name: 'SelFieldModal',
    components: { BasicModal, Select, SelectOption: Select.Option, Card },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const options = ref([]);
      const options2 = ref([]);
      const selectedValue = ref([]);
      const selectedValue2 = ref([]);
      const { createMessage } = useMessage();
      const formCode = ref('');
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        setModalProps({ confirmLoading: false, width: '50%' });
        // isUpdate.value = !!data?.isUpdate;
        if (isArray(data.options)) {
          options.value = data.options.filter((item) => item.macroType != 'nest_table');
        }
        selectedValue.value = [];
        if (data.userRealName) {
          const splits = data.userRealName.split(',');
          options.value.forEach((item) => {
            if (splits.includes(item.title)) selectedValue.value.push(item.name);
          });
        }
        formCode.value = data?.formCode;
        getNestFields();
      });
      //获取主表中嵌套表
      const getNestFields = async () => {
        try {
          const res = await getFormGetNestFields({ formCode: unref(formCode) });
          options2.value = res;
        } catch (err) {
          console.log(err);
        }
      };

      const getTitle = '选择';

      async function handleSubmit() {
        try {
          setModalProps({ confirmLoading: true });
          if (selectedValue.value.length == 0) {
            createMessage.warning('选择数据不能为空');
            return;
          }
          const selectedList: Recordable[] = options.value.filter((item) =>
            selectedValue.value.includes(item.name),
          );
          const params = {
            value: selectedList.map((item) => item.name).join(','),
            label: selectedList.map((item) => item.title).join(','),
          };
          closeModal();
          emit('success', params);
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      const filterOption = (inputValue: string, option: DataList) => {
        return option.label.indexOf(inputValue) > -1;
      };
      const handleForm = () => {
        try {
          setModalProps({ confirmLoading: true });
          if (selectedValue.value.length == 0) {
            createMessage.warning('选择数据不能为空');
            return;
          }
          const selectedList: Recordable[] = options.value.filter((item) =>
            selectedValue.value.includes(item.name),
          );
          const params = {
            value: selectedList.map((item) => item.name).join(','),
            label: selectedList.map((item) => item.title).join(','),
          };
          closeModal();
          emit('success', params);
        } finally {
          setModalProps({ confirmLoading: false });
        }
      };
      const handleFormNest = () => {
        try {
          setModalProps({ confirmLoading: true });
          if (selectedValue2.value.length == 0) {
            createMessage.warning('选择数据不能为空');
            return;
          }
          const selectedList: Recordable[] = options2.value.filter((item) =>
            selectedValue2.value.includes(item.name),
          );
          const params = {
            value: selectedList.map((item) => item.name).join(','),
            label: selectedList.map((item) => item.title).join(','),
          };
          closeModal();
          emit('success', params);
        } finally {
          setModalProps({ confirmLoading: false });
        }
      };
      return {
        registerModal,
        getTitle,
        handleSubmit,
        filterOption,
        options,
        options2,
        selectedValue,
        selectedValue2,
        handleForm,
        handleFormNest,
      };
    },
  });
</script>
